using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
using Crystalbyte.Equinox.Imap;
using Crystalbyte.Equinox.Security;
using Crystalbyte.Equinox.Imap.Commands;
using Crystalbyte.Equinox.Imap.Linq;
using System.Diagnostics;
using Crystalbyte.Equinox.Security.Authentication;
using System.Threading;
using System.Collections.ObjectModel;


namespace Application4
{
    partial class App
    {
        public App()
        {
            InitializeComponent();
        }

        private MainPage mainpage;
        private Setting setting = new Setting();
        private ObservableVector<object> mbox = new ObservableVector<object>();
        private SynchronizationContext context;

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            context = SynchronizationContext.Current;
            mainpage = new MainPage();
            mainpage.setting = this.setting;
            mainpage.mails = mbox;
            Window.Current.Content = mainpage;
            Window.Current.Activate();
            if (setting.Username != null && setting.Username.Length > 0
                && setting.Password != null && setting.Password.Length > 0)
            {
                fetchMailAsync();
            }
        }

        public async void fetchMailAsync()
        {
            ThreadPool.QueueUserWorkItem(x => fetchMail());
        }

        public void fetchMail()
        {
            using (var client = new ImapClient())
            {
                client.Security = SecurityPolicies.Explicit;
                client.Connect("imap.gmail.com", 993);
                var res = client.Authenticate(setting.Username, setting.Password, Crystalbyte.Equinox.Security.Authentication.SaslMechanics.Login);
                client.Select("INBOX");
                
                var q = client.Messages
                    .Where(x => x.Date > DateTime.Now.AddDays(-7))
                    .Select(x => x.Envelope);

                context.Send(new SendOrPostCallback(delegate(object state)
                {
                    mbox.Clear();
                }), null);
                foreach (var it in q)
                {
                    context.Send(new SendOrPostCallback(delegate(object state)
                    {
                        // In case of parse error, it will be null
                        if (it != null) { mbox.Add(new MItem(it)); }
                    }), null);
                }
            }
        }
    }
}
